// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DifferentialDriveAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Navigation.Runtime.Motion
{
    using System;
    using System.IO;
    using System.Runtime.Serialization;  

    using Microsoft.Robotics.Hardware.DAC;
    using Microsoft.Robotics.Hardware.Runtime.DAC;
    using Microsoft.Robotics.IO;
    using Microsoft.Robotics.Navigation.Localization;
    using Microsoft.Robotics.Navigation.Motion;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Tracing;    

    /// <summary>
    /// Create a drive feedback state message by updating state from a DifferentialDriveMessage
    /// 1) Heading estimates by adding in the increment from the last received message
    /// 2) Drive (X,Y) locations by adding increment from last received message
    /// </summary>
    [DataContract]
    public class DifferentialDriveAgent : ConsumerProducerAgent<DifferentialDriveMessage, SimpleAgentMessage<DriveFeedbackState>>
    {
        /// <summary>
        /// Robot configuration folder which contains camera calibration information.
        /// </summary>
        [DataMember(Name = "RobotConfigFolder")]
        private readonly string robotConfigFolder;

        /// <summary>
        /// A DriveFeedback object that accumulates drive feedback over time.
        /// </summary>
        private DifferentialDriveStateUpdate differentialDriveStateUpdate;

        /// <summary>
        /// Wheel calibration data
        /// </summary>
        private DifferentialWheelCalibration wheelCalibration;

        /// <summary>
        /// Odometry noise data
        /// </summary>
        private OdometryNoiseModelParams odometryNoiseParams;

        /// <summary>
        /// Initializes a new instance of the <see cref="DifferentialDriveAgent"/> class. 
        /// </summary>
        /// <param name="name">Processor name</param>
        /// <param name="producer">Message producer - normally HeartBeatAgent</param>
        /// <param name="robotConfigFolder">Robot config folder</param>
        public DifferentialDriveAgent(string name, IProducer<DifferentialDriveMessage> producer, string robotConfigFolder)
            : base(name, producer.Name)
        {
            this.robotConfigFolder = robotConfigFolder;
        }

        /// <summary>
        /// Activates this agent and all its upstream producers
        /// </summary>
        public override void OnActivated()
        {
            base.OnActivated();

            // This will clear the internal state, so re-activating the agent after deactivating it will start from the clean slate
            // as opposed to hang on to the old state
            this.differentialDriveStateUpdate = new DifferentialDriveStateUpdate(this.wheelCalibration, this.odometryNoiseParams);
        }

        /// <summary>
        /// Called after construction, to allow the agent to finish initialization. 
        /// </summary>
        /// <param name="locator">A locator that can be used to find other agents.</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
            
            this.wheelCalibration = DataLoader<DifferentialWheelCalibration>.ImportData(Path.Combine(this.robotConfigFolder, DifferentialWheelCalibration.Filename));

            if (this.wheelCalibration == null)
            {
                throw new System.ArgumentException(string.Format("Could not load wheel calibration file {0} from {1}", DifferentialWheelCalibration.Filename, this.robotConfigFolder));
            }

            this.odometryNoiseParams = DataLoader<OdometryNoiseModelParams>.ImportData(
            Path.Combine(this.robotConfigFolder, OdometryNoiseModelParams.Filename));

            if (this.odometryNoiseParams == null)
            {
                throw new ArgumentNullException(string.Format("Could not load odometry noise model file {0} from {1}", this.robotConfigFolder, OdometryNoiseModelParams.Filename));
            }
            else
            {
                TraceOut.Info(TraceContexts.Nav, "Loaded noise params file {0} from {1}", OdometryNoiseModelParams.Filename, this.robotConfigFolder);
            }
        }

        /// <summary>
        /// Receive , process and republish a message
        /// </summary>
        /// <param name="inMessage">Message to process</param>
        public override void Receive(DifferentialDriveMessage inMessage)
        {
            if (inMessage.State.Count > 0)
            {
                DriveFeedbackState updatedMessage = this.differentialDriveStateUpdate.UpdateDriveFeedback(inMessage.State[0]);

                if (this.differentialDriveStateUpdate != null)
                {
                    this.Publisher.Post(new SimpleAgentMessage<DriveFeedbackState>(updatedMessage, inMessage));
                }
            }
        }
    }
}
